﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CMU.Certificates;

namespace CMU.Manage
{
    public partial class UCSinhVien : UserControl
    {
        CertificateEntities context = new CertificateEntities();
        public UCSinhVien()
        {
            InitializeComponent();
        }

        // LOAD
        private void UCSinhVien_Load(object sender, EventArgs e)
        {
            var loadsv = from sv in context.SinhVien
                         select sv;
            dataGridView1.DataSource = loadsv.ToList();
            dataGridView1.Refresh();

            var khoahoc = from kh in context.KhoaHoc
                          select kh;
            comboBox1.DataSource = khoahoc.ToList<KhoaHoc>();
            comboBox1.DisplayMember = "TenKH";
            comboBox1.ValueMember = "Id";
        }

        // ADD
        private void button2_Click(object sender, EventArgs e)
        {

            SinhVien sv = new SinhVien();
            sv.MaSV = textBox2.Text;
            sv.Gender = byte.Parse(textBox3.Text);
            sv.FirstName = textBox4.Text;
            sv.MiddleName = textBox5.Text;
            sv.LastName = textBox6.Text;
            context.SinhVien.Add(sv);
            int count = context.SaveChanges();
            if (count > 0)
            {
                MessageBox.Show("Da them moi");
                UCSinhVien_Load(sender, e);
            }
            else
                MessageBox.Show("Da ton tai");
        }

        private void button6_Click(object sender, EventArgs e)
        {
            int svID;
            if (Int32.TryParse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString(), out svID))
            {
                using (CertificateEntities newcontext = new CertificateEntities())
                {
                    SinhVien sv = new SinhVien() { Id = svID };
                    newcontext.SinhVien.Attach(sv);
                    //context.ObjectStateManger.ChangeObjectState(mh, EntityState.Deleted);
                    //newcontext.Entry(mh).State = System.Data.EntityState.Deleted;
                    newcontext.SinhVien.Remove(sv);

                    int count = newcontext.SaveChanges();
                    if (count > 0)
                    {
                        MessageBox.Show("Da xoa");
                        UCSinhVien_Load(sender, e);
                    }
                    else
                    {
                        MessageBox.Show("Mon Hoc da duoc lien ket");
                    }

                }
            }
        }
    }
}
